// LeanCloud服务模块
// 由于无法使用npm安装依赖，我们将使用LeanCloud的REST API进行操作

// LeanCloud配置信息
const LEANCLOUD_CONFIG = {
  APP_ID: 'UhRgTlt0jH0D69h7nJeCxoMz-gzGzoHsz',
  APP_KEY: 'dC90fu68TK6ARLxC4zd8aPE2',
  API_SERVER: 'https://uhrgtlt0.lc-cn-n1-shared.com',
  REST_API_KEY: 'dC90fu68TK6ARLxC4zd8aPE2', // 添加REST API Key
  MASTER_KEY: 'tSMTCHJtZJOCKUkpVuSbYOHt' // 可选: 添加Master Key，如果您有的话
};

// 微信小程序配置
const WECHAT_CONFIG = {
  APP_ID: 'wx0280ba8b92e95307',
  APP_SECRET: 'ed025e06d96b985fdf447e92f24c5c3b'
};

// 初始化LeanCloud服务
function initLeanCloud() {
  console.log('LeanCloud初始化成功');
  return LEANCLOUD_CONFIG;
}

// 获取请求头
function getHeaders() {
  return {
    'X-LC-Id': LEANCLOUD_CONFIG.APP_ID,
    'X-LC-Key': LEANCLOUD_CONFIG.APP_KEY,
    'Content-Type': 'application/json'
  };
}

// 创建对象
function createObject(className, data) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/classes/${className}`,
      method: 'POST',
      header: getHeaders(),
      data: data,
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 查询对象
function queryObjects(className, query = {}) {
  let url = `${LEANCLOUD_CONFIG.API_SERVER}/1.1/classes/${className}`;
  
  // 如果有查询条件，将其转换为JSON字符串并添加到URL中
  if (Object.keys(query).length > 0) {
    url += `?where=${encodeURIComponent(JSON.stringify(query))}`;
  }
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      method: 'GET',
      header: getHeaders(),
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 获取单个对象
function getObject(className, objectId) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/classes/${className}/${objectId}`,
      method: 'GET',
      header: getHeaders(),
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 更新对象
function updateObject(className, objectId, data) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/classes/${className}/${objectId}`,
      method: 'PUT',
      header: getHeaders(),
      data: data,
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 删除对象
function deleteObject(className, objectId) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/classes/${className}/${objectId}`,
      method: 'DELETE',
      header: getHeaders(),
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 用户注册
function userSignUp(username, password, email = '', phone = '') {
  const userData = {
    username,
    password,
  };
  
  if (email) userData.email = email;
  if (phone) userData.mobilePhoneNumber = phone;
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/users`,
      method: 'POST',
      header: getHeaders(),
      data: userData,
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 用户登录
function userLogin(username, password) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/login`,
      method: 'POST',
      header: getHeaders(),
      data: {
        username,
        password
      },
      success: (res) => {
        // 保存用户的sessionToken
        if (res.data && res.data.sessionToken) {
          wx.setStorageSync('leancloud_session_token', res.data.sessionToken);
          wx.setStorageSync('leancloud_user_id', res.data.objectId);
        }
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 获取当前用户
function getCurrentUser() {
  const sessionToken = wx.getStorageSync('leancloud_session_token');
  if (!sessionToken) {
    return Promise.resolve(null);
  }
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/users/me`,
      method: 'GET',
      header: {
        ...getHeaders(),
        'X-LC-Session': sessionToken
      },
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 用户登出
function userLogout() {
  const sessionToken = wx.getStorageSync('leancloud_session_token');
  if (!sessionToken) {
    return Promise.resolve();
  }
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/logout`,
      method: 'POST',
      header: {
        ...getHeaders(),
        'X-LC-Session': sessionToken
      },
      success: (res) => {
        wx.removeStorageSync('leancloud_session_token');
        wx.removeStorageSync('leancloud_user_id');
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 上传文件
function uploadFile(filePath, fileName) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/files/${fileName}`,
      filePath: filePath,
      name: 'file',
      header: getHeaders(),
      success: (res) => {
        if (typeof res.data === 'string') {
          try {
            const data = JSON.parse(res.data);
            resolve(data);
          } catch (e) {
            reject(e);
          }
        } else {
          resolve(res.data);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 创建默认账号(备用方法)
function createDefaultAccount(resolve, reject) {
  console.log('尝试创建普通账户作为备用方案');
  // 生成随机用户名和密码
  const randomUsername = 'wx_user_' + Math.random().toString(36).substring(2, 10);
  const randomPassword = Math.random().toString(36).substring(2, 10);
  
  wx.request({
    url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/users`,
    method: 'POST',
    header: getHeaders(),
    data: {
      username: randomUsername,
      password: randomPassword
    },
    success: (res) => {
      console.log('创建普通账户响应:', res);
      if (res.statusCode >= 200 && res.statusCode < 300) {
        // 保存登录态
        if (res.data && res.data.sessionToken) {
          wx.setStorageSync('leancloud_session_token', res.data.sessionToken);
          wx.setStorageSync('leancloud_user_id', res.data.objectId);
          // 保存用户名和密码以便后续登录
          wx.setStorageSync('leancloud_username', randomUsername);
          wx.setStorageSync('leancloud_password', randomPassword);
          console.log('普通账户登录成功，保存登录信息');
        }
        resolve(res.data);
      } else {
        console.error('创建普通账户失败:', res);
        reject(new Error(res.data ? res.data.error : '登录失败'));
      }
    },
    fail: (err) => {
      console.error('创建普通账户请求失败:', err);
      reject(err);
    }
  });
}

// 微信小程序登录
function wechatLogin() {
  return new Promise((resolve, reject) => {
    // 先尝试查找已保存的普通账号信息
    const username = wx.getStorageSync('leancloud_username');
    const password = wx.getStorageSync('leancloud_password');
    
    if (username && password) {
      console.log('发现已保存的账号信息，尝试直接登录');
      // 使用保存的账号信息直接登录
      wx.request({
        url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/login`,
        method: 'POST',
        header: getHeaders(),
        data: {
          username,
          password
        },
        success: (res) => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            console.log('使用已保存账号登录成功');
            // 保存登录态
            if (res.data && res.data.sessionToken) {
              wx.setStorageSync('leancloud_session_token', res.data.sessionToken);
              wx.setStorageSync('leancloud_user_id', res.data.objectId);
            }
            resolve(res.data);
            return;
          } else {
            console.log('已保存账号登录失败，尝试创建新账号');
            // 创建新账号
            createDefaultAccount(resolve, reject);
          }
        },
        fail: () => {
          console.log('已保存账号登录请求失败，尝试创建新账号');
          // 创建新账号
          createDefaultAccount(resolve, reject);
        }
      });
      return;
    }
    
    // 如果没有保存的账号，尝试微信登录
    console.log('开始调用微信登录API');
    wx.login({
      success: (loginRes) => {
        if (loginRes.code) {
          console.log('成功获取微信code:', loginRes.code);
          
          // 格式化LeanCloud要求的authData格式
          const authData = {
            weapp: {  // 注意：应使用weapp而不是lc_weapp
              code: loginRes.code
              // 不再在请求中包含appid和secret，这些应在LeanCloud后台配置
            }
          };
          
          console.log('发送认证数据:', authData);
          
          // 尝试使用微信code创建或登录账号
          wx.request({
            url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/users`,
            method: 'POST',
            header: getHeaders(),
            data: {
              authData: authData
            },
            success: (res) => {
              console.log('用户创建/登录响应:', res);
              if (res.statusCode >= 200 && res.statusCode < 300) {
                console.log('微信登录成功');
                // 保存登录态
                if (res.data && res.data.sessionToken) {
                  wx.setStorageSync('leancloud_session_token', res.data.sessionToken);
                  wx.setStorageSync('leancloud_user_id', res.data.objectId);
                }
                resolve(res.data);
              } else if (res.statusCode === 400 && res.data && res.data.code === 1) {
                // 如果是appid和secret配置问题，使用备用方案
                console.log('LeanCloud未配置微信小程序信息，使用备用方案');
                createDefaultAccount(resolve, reject);
              } else {
                console.log('微信登录失败，尝试创建普通账号');
                // 尝试创建普通账号
                createDefaultAccount(resolve, reject);
              }
            },
            fail: (failErr) => {
              console.log('微信登录请求失败:', failErr);
              // 尝试创建普通账号
              createDefaultAccount(resolve, reject);
            }
          });
        } else {
          console.log('获取微信code失败，尝试创建普通账号');
          // 尝试创建普通账号
          createDefaultAccount(resolve, reject);
        }
      },
      fail: () => {
        console.log('调用微信登录API失败，尝试创建普通账号');
        // 尝试创建普通账号
        createDefaultAccount(resolve, reject);
      }
    });
  });
}

// 关联微信账号
function linkWithWechat(code) {
  const sessionToken = wx.getStorageSync('leancloud_session_token');
  if (!sessionToken) {
    return Promise.reject(new Error('用户未登录'));
  }
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/users/me/authData/weapp`,
      method: 'PUT',
      header: {
        ...getHeaders(),
        'X-LC-Session': sessionToken
      },
      data: {
        code: code
        // 不再包含appid和secret，这些应在LeanCloud后台配置
      },
      success: (res) => {
        console.log('关联微信账号响应:', res);
        resolve(res.data);
      },
      fail: (err) => {
        console.error('关联微信账号失败:', err);
        reject(err);
      }
    });
  });
}

// 使用微信用户信息更新用户资料
function updateUserInfo(userInfo) {
  const sessionToken = wx.getStorageSync('leancloud_session_token');
  const userId = wx.getStorageSync('leancloud_user_id');
  
  console.log('更新用户资料:', { userInfo, sessionToken, userId });
  
  if (!sessionToken || !userId) {
    console.error('用户未登录，无法更新资料');
    return Promise.reject(new Error('用户未登录'));
  }
  
  return new Promise((resolve, reject) => {
    // 构建更新数据
    const updateData = {};
    
    // 兼容微信新旧数据格式
    if (userInfo.nickName || userInfo.nickname) {
      updateData.nickname = userInfo.nickName || userInfo.nickname;
    }
    
    if (userInfo.avatarUrl || userInfo.avatarurl) {
      updateData.avatarUrl = userInfo.avatarUrl || userInfo.avatarurl;
    }
    
    // 只添加存在的可选字段
    if (userInfo.gender !== undefined) updateData.gender = userInfo.gender;
    if (userInfo.country) updateData.country = userInfo.country;
    if (userInfo.province) updateData.province = userInfo.province;
    if (userInfo.city) updateData.city = userInfo.city;
    
    // 如果没有任何可更新字段，直接返回成功
    if (Object.keys(updateData).length === 0) {
      console.log('无用户数据需要更新');
      return resolve({ success: true });
    }
    
    console.log('发送更新用户资料请求:', updateData);
    
    wx.request({
      url: `${LEANCLOUD_CONFIG.API_SERVER}/1.1/users/${userId}`,
      method: 'PUT',
      header: {
        ...getHeaders(),
        'X-LC-Session': sessionToken
      },
      data: updateData,
      success: (res) => {
        console.log('更新用户资料响应:', res);
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          console.error('更新用户资料请求失败:', res);
          reject(new Error(res.data ? res.data.error : '更新用户资料失败'));
        }
      },
      fail: (err) => {
        console.error('更新用户资料请求错误:', err);
        reject(err);
      }
    });
  });
}

export default {
  init: initLeanCloud,
  create: createObject,
  query: queryObjects,
  get: getObject,
  update: updateObject,
  delete: deleteObject,
  user: {
    signUp: userSignUp,
    login: userLogin,
    logout: userLogout,
    getCurrent: getCurrentUser,
    wechatLogin: wechatLogin,
    linkWithWechat: linkWithWechat,
    updateUserInfo: updateUserInfo
  },
  file: {
    upload: uploadFile
  }
}; 